#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "tree.h"
#include "arch.h"
#include "dearch.h"

#define MAX_PARAM_NUMBER  4
#define MIN_PARAM_NUMBER 2

#define FUNCTION 1
#define FILE_IN 2
#define FILE_OUT 3

#define HELP "--help"
#define ARCHIVATE "-a"
#define DEARCHIVATE "-d"

enum errors {
    OK = 0,
    ERROR_PARAM_NUMBER = -1,
    ERROR_FILE_OPEN = -2,
    ERROR_OUT_OF_MEMORY = -3,
    ERROR_NAME_FUNCTION = -4,
    ERROR_FILE_EMPTY = -5,
    ERROR_FILE_CONTENT = -6
};

int errorHandler (enum errors error);

void showHelp ();

int main (int argc, char ** argv) {
    enum errors error = OK;

    if ((argc > MAX_PARAM_NUMBER) || (argc < MIN_PARAM_NUMBER)){ // аргументов в функции должно быть не больше 4
        error = ERROR_PARAM_NUMBER;
        return errorHandler (error);
    }

    if (strcmp (argv[FUNCTION], HELP) == 0) { // помощь
        showHelp ();
        return OK;
    } else if ((argc == MAX_PARAM_NUMBER) && (strcmp (argv[FUNCTION], ARCHIVATE) == 0)) { // архивация
        error = archivate (argv[FILE_IN], argv[FILE_OUT]);
    } else if ((argc == MAX_PARAM_NUMBER) && (strcmp (argv[FUNCTION], DEARCHIVATE) == 0)) { // деархивация
        error = dearchivate (argv[FILE_IN], argv[FILE_OUT]);
    } else if ((strcmp (argv[FUNCTION], ARCHIVATE) != 0) && (strcmp (argv[FUNCTION], DEARCHIVATE) != 0)) {
        return errorHandler (ERROR_NAME_FUNCTION);
    } else {
        return errorHandler (ERROR_PARAM_NUMBER);
    }

    return errorHandler (error);
}

int errorHandler (enum errors error) {
    switch (error) {
        case OK : {
            printf ("Process complite.\n");
            break;
        }
        case ERROR_PARAM_NUMBER : {
            printf ("Wrong number of parametrs.\nWrite --help option to look through the help.\n");
            break;
        }
        case ERROR_FILE_OPEN : {
            printf ("Program can't open files you write.\n");
            break;
        }
        case ERROR_OUT_OF_MEMORY : {
            printf ("Out of memory!");
            break;
        }
        case ERROR_NAME_FUNCTION : {
            printf ("Wrong name of option.\nWrite --help option to look through the help.\n");
            break;
        }
        case ERROR_FILE_EMPTY : {
            printf ("File, which you want to archive is empty.\n");
            break;
        }
        case ERROR_FILE_CONTENT : {
            printf ("Another file format.\n");
            break;
        }
    }

    return error;
}

void showHelp () {
    printf ("-a file_in file_out\t - archive file_in to file_out\n-d file_in file_out\t - dearchive file_in to file_out\n--help\t - to call this message\n");
    return;
}
